<template>
  <div class="recipe-form-container" style="width: 80%; margin: 0 auto;">
    <h1>新增食谱</h1>
    <a-form :model="recipe" :label-col="{ span: 4 }" :wrapper-col="{ span: 16 }" @submit.prevent="submitForm">
      <a-form-item label="食谱名">
        <a-input v-model:value="recipe.title" required placeholder="请输入食谱名称" />
      </a-form-item>
      <a-form-item label="食谱描述">
        <a-input v-model:value="recipe.description" required placeholder="请输入食谱描述" />
      </a-form-item>
      <a-form-item label="食材列表">
        <a-textarea v-model:value="recipe.ingredients" :rows="4" required placeholder="请输入食材列表" />
      </a-form-item>
      <a-form-item label="制作步骤">
        <a-textarea v-model:value="recipe.instructions" :rows="8" required placeholder="请输入制作步骤" />
      </a-form-item>
      <a-form-item label="食谱图片">
        <a-upload
            name="file"
            action="/upload"
            list-type="picture-card"
            :file-list="fileList"
            :before-upload="beforeUpload"
            @change="handleChange"
            accept=".jpg,.jpeg,.png"
        >
          <div v-if="fileList.length < 1">
            <PlusOutlined />
            <div style="margin-top: 8px">上传图片</div>
          </div>
        </a-upload>
        <p class="ant-upload-text">最多支持上传1张图片</p>
      </a-form-item>
      <a-form-item :wrapper-col="{ offset: 4, span: 16 }">
        <a-button type="primary" html-type="submit">提交</a-button>
      </a-form-item>
    </a-form>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import axios from 'axios';
import { PlusOutlined } from '@ant-design/icons-vue';
import { notification } from 'ant-design-vue';
import router from '@/router';

// 初始状态
const recipe = reactive({
  title: '',
  description: '',
  ingredients: '',
  instructions: '',
  file: null // 存储单个文件对象
});

// 文件列表
const fileList = ref([]);

// 在上传之前预览图片
const beforeUpload = (file) => {
  const isJPGOrPNG = file.type === 'image/jpeg' || file.type === 'image/png';
  if (!isJPGOrPNG) {
    notification.error({
      message: '只能上传 JPG/PNG 图片',
    });
  }
  const isLt2M = file.size / 1024 / 1024 < 2;
  if (!isLt2M) {
    notification.error({
      message: '图片大小不能超过 2MB!',
    });
  }
  if (isJPGOrPNG && isLt2M) {
    fileList.value = [file];
    recipe.file = file;
  }
  return false; // 阻止实际上传
};

// 处理文件变化
const handleChange = (info) => {
  const { fileList } = info;
  fileList.value = fileList;
};

// 提交表单
const submitForm = () => {
  const token = localStorage.getItem('Token');

  // 如果存在token，则设置请求头
  const config = {
    headers: {
      'Token': token,
      'Content-Type': 'multipart/form-data',
    }
  };
  if (!recipe.title || !recipe.description || !recipe.ingredients || !recipe.instructions || !recipe.file) {
    notification.error({
      message: '请填写完整的信息',
    });
    return;
  }

  // 创建 FormData 对象
  const formData = new FormData();
  formData.append('title', recipe.title);
  formData.append('description', recipe.description);
  formData.append('ingredients', recipe.ingredients);
  formData.append('instructions', recipe.instructions);
  formData.append('file', recipe.file, recipe.file.name);

  // 发送 POST 请求
  axios.post('/recipe', formData, config)
      .then(response => {
        const data = response.data;
        if (data.code === 0) {
          notification.success({
            description: "新增成功！",
          });
          // 清空表单
          recipe.title = '';
          recipe.description = '';
          recipe.ingredients = '';
          recipe.instructions = '';
          recipe.file = null;
          fileList.value = [];
          router.push("/recipelist");
        } else {
          notification.error({
            description: data.message,
          });
        }
      })
      .catch(error => {
        console.error('Add error:', error);
        notification.error({
          description: '新增失败',
        });
      });
};

// 挂载时初始化
onMounted(() => {
  // 初始化操作
});
</script>

<style scoped>
.recipe-form-container {
  background-color: #fff;
  padding: 20px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  margin-top: 20px;
}

.recipe-form-container h1 {
  text-align: center;
  margin-bottom: 20px;
}

.ant-form-item {
  margin-bottom: 16px;
}

.ant-upload-text {
  margin-top: 8px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 14px;
}

.ant-upload-picture-card {
  width: 100%;
  height: 200px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
}

.ant-upload-picture-card .anticon {
  font-size: 32px;
}

.ant-upload-picture-card .ant-upload-text {
  font-size: 16px;
}
</style>